import requests
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from app.models.user import User
from app.extensions import db
from app.utils.response import success_response
from app.utils.validators import validate_wechat_code
from app.utils.decorators import handle_errors

auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')


@auth_bp.route('/login', methods=['POST'])
@handle_errors
def wechat_login():
    """微信小程序登录"""
    data = request.get_json()
    code = data.get('code')
    user_info = data.get('userInfo', {})
    
    if not code:
        return jsonify({'error': '缺少微信授权码'}), 400
    
    # 向微信服务器验证code，获取openid
    openid = validate_wechat_code(code)
    if not openid:
        return jsonify({'error': '微信授权验证失败'}), 401
    
    # 查找或创建用户
    user = User.query.filter_by(openid=openid).first()
    if not user:
        user = User(
            openid=openid,
            nickname=f"微信用户{openid[:4]}",
            avatar_url='',
            password='123456'
        )
        db.session.add(user)
        db.session.commit()
    else:
        # 更新用户信息
        if user_info.get('nickName'):
            user.nickname = user_info.get('nickName')
        if user_info.get('avatarUrl'):
            user.avatar_url = user_info.get('avatarUrl')
        db.session.commit()
    
    # 生成JWT token
    access_token = create_access_token(identity=str(user.id))
    refresh_token = create_refresh_token(identity=str(user.id))
    
    return success_response(
        data={
            'access_token':access_token,
            'refresh_token': refresh_token,
            'user':user.to_dict()
        }
    )


@auth_bp.route('/login/password', methods=['POST'])
@handle_errors
def password_login():
    """用户名密码登录"""
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    if not username or not password:
        return jsonify({'code':201,'message': '用户名和密码不能为空'})
    
    # 查找用户
    user = User.query.filter_by(nickname=username).first()
    if not user or not user.check_password(password):
        return jsonify({'code':201,'message': '用户名或密码错误'})
    
    # 生成JWT token
    access_token = create_access_token(identity=str(user.id))
    refresh_token = create_refresh_token(identity=str(user.id))
    
    return jsonify({
        'code':200,
        'data': {
            'access_token': access_token,
            'refresh_token': refresh_token,
            'user': user.to_dict()
        }
    })


@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
@handle_errors
def refresh_token():
    """刷新访问令牌"""
    current_user_id = get_jwt_identity()
    new_token = create_access_token(identity=current_user_id)
    
    return jsonify({
        'access_token': new_token
    })


@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
@handle_errors
def get_profile():
    """获取当前用户信息"""
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    
    return jsonify({
        'user': user.to_dict(),
        'statistics': user.get_statistics()
    })


@auth_bp.route('/profile', methods=['PUT'])
@jwt_required()
@handle_errors
def update_profile():
    """更新用户信息"""
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    
    data = request.get_json()
    
    # 更新允许的字段
    if 'nickname' in data:
        user.nickname = data['nickname']
    if 'phone' in data:
        user.phone = data['phone']
    if 'avatar_url' in data:
        user.avatar_url = data['avatar_url']
    
    db.session.commit()
    
    return jsonify({
        'message': '用户信息更新成功',
        'user': user.to_dict()
    })